package com.kailong.service;

import com.kailong.entity.RequestConditionEntity;
import com.kailong.exception.BusinessException;
import com.kailong.mapper.CustomerMapper;
import com.kailong.util.BetweenTimeUtil;
import com.kailong.util.ExcelUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.List;

@Slf4j
public abstract class BaseService<K, V> {

    /**
     * 获取BaseMapper
     *
     * @return BaseMapper
     */
    protected abstract CustomerMapper getBaseMapper();


    /**
     * 用户自定义导出逻辑
     *
     * @param v 查询条件
     * @return 是否自定义
     */
    public boolean customizeExport(V v) {
        return false;
    }

    /**
     * 公共excel导出方法
     *
     * @param v         查询条件
     * @param fileName  文件名称
     * @param clazzName 实体类名称
     * @IOException 异常
     */
    public void export(V v, String fileName, String clazzName) {
        if (customizeExport(v)) {
            return;
        }

        doExport(v, fileName, clazzName);
    }

    private void doExport(V v, String fileName, String clazzName) {
        RequestConditionEntity conditionEntity = (RequestConditionEntity) v;
        BetweenTimeUtil.parseTime(conditionEntity);
        conditionEntity.setPageSize(0);
        List<K> dataEntities = getBaseMapper().searchByCondition(conditionEntity);
        try {
            ExcelUtil.exportExcel(fileName, Class.forName(clazzName), dataEntities);
        } catch (ClassNotFoundException e) {
            log.error("数据导出异常，没有找到:{}", clazzName);
            throw new BusinessException(String.format("数据导出异常，没有找到:%s", clazzName));
        } catch (IOException e) {
            log.error("数据导出异常，原因:", e);
            throw new BusinessException("数据导出异常，请稍后重试");
        }
    }
}